import React from 'react';
import styles from './style';
import {
    Text,
    SafeAreaView,
    ImageBackground,
    Image,
    View,
    TouchableOpacity,
    Platform,
    Alert,
    DeviceEventEmitter,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Back from '../../common/component/back';
import { getPhotosDetailById } from '../../common/api/photos';
import { getUserInfo } from '../../common/api/user';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { defalutAvatar } from '../../util/constants';
import { userFocusPhotos, userUnfocusPhotos } from '../../common/api/userFocusPhotos';
import { hasAndroidPermission } from '../../util/permission';
import RNFS from 'react-native-fs';
import CameraRoll from '@react-native-community/cameraroll';
import { updatePhotosDownCount } from '../../common/api/photosProfile';
const dz = require('../../common/img/dz.png');
const share = require('../../common/img/share.png');
const downLoad = require('../../common/img/download.png');
const sc = require('../../common/img/sc.png');
export default class Detail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            _id: '',
            show: true,
            showOther: false,
            detail: {
                title: '',
                desc: '',
                user: {
                    nickname: '',
                    avatar: '',
                },
            },
        };
    }

    componentDidMount() {
        this.getData();
    }
    componentDidUpdate() {
        const { _id } = this.props.route.params;
        if (this.state._id && _id !== this.state._id) {
            this.getData();
        }
    }
    focus = async () => {
        const { currentUserIsFocus, _id } = this.state.detail;
        if (!this.state.detail.currentUserIsFocus) {
            await userFocusPhotos(_id);
        } else {
            await userUnfocusPhotos(_id);
        }
        this.getData();
    };
    getUserInfo = async () => {
        let userInfo = await AsyncStorage.getItem('userInfo');
        if (userInfo) {
            const parseUserInfo = JSON.parse(userInfo);
            if (parseUserInfo) {
                userInfo = parseUserInfo;
            }
        }
        userInfo = userInfo || (await getUserInfo());
        return userInfo;
    };
    getData = async () => {
        const { _id } = this.props.route.params;
        const [userInfo, res] = await Promise.all([this.getUserInfo(), getPhotosDetailById(_id)]);
        this.setState({
            detail: res,
            showOther: userInfo._id !== res.user._id,
            _id: _id,
        });
    };
    updateDownCount = async () => {
        await updatePhotosDownCount(this.state.detail._id);
        this.getData();
    };
    addHistory = async () => {
        const url = this.props.route.params.img.uri;
        const { title, _id } = this.state.detail;
        let downHistory = await AsyncStorage.getItem('downHistory');
        downHistory = downHistory ? JSON.parse(downHistory) : [];
        downHistory.push({
            title,
            createAt: new Date(),
            url,
            _id,
        });
        AsyncStorage.setItem('downHistory', JSON.stringify(downHistory));
    };
    saveToCameraroll = async () => {
        const { route } = this.props;
        const bg = route.params.img;
        const url = bg.uri;
        const fileExtension = url.split('.').pop().toLowerCase();
        if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
            // 提示
            return Alert.alert('请打开相册获取权限!');
        }
        let timestamp = new Date().getTime();
        let random = String(Math.random() * 1000000);
        let dirs =
            Platform.OS === 'ios'
                ? RNFS.DocumentDirectoryPath
                : 'file://' + RNFS.ExternalStorageDirectoryPath;
        const toPath = `${dirs}/${timestamp + random}.${fileExtension}`;
        console.log('url==', url);
        console.log('toPath==', toPath);
        const options = {
            fromUrl: url,
            toFile: toPath,
            background: true,
            begin: res => {},
            progress: res => {},
        };
        try {
            const ret = RNFS.downloadFile(options);
            await ret.promise;
            const filePath = toPath.startsWith('file://') ? toPath : 'file://' + toPath;
            console.log('filePath===', filePath);
            await CameraRoll.save(filePath, { album: 'zoneyet_photos' });
            // console.log('saveToCameraRoll success');
            RNFS.unlink(toPath);
            this.updateDownCount();
            this.addHistory();
            DeviceEventEmitter.emit('RefreshMineData');

            return Alert.alert('保存成功！', '已保存到系统相册');
        } catch (error) {
            if (error?.message?.includes('Access to photo library was denied')) {
                return Alert.alert('请打开相册获取权限');
            }
            Alert.alert('保存失败');
            console.log(' saveToCameraRollerror', error);
        }
    };
    render() {
        let { navigation, route } = this.props;
        const { detail, showOther } = this.state;
        let bg = route.params.img;
        // let status = route.params.status;
        const avatar = { uri: detail.user.avatar || defalutAvatar };
        return (
            <ImageBackground source={bg} style={styles.bgImg}>
                <SafeAreaView style={styles.content}>
                    <Back navigation={navigation} witheIcon />
                    <Animatable.View style={styles.contentText} animation="slideInUp">
                        <TouchableOpacity
                            activeOpacity={1}
                            style={styles.topcontent}
                            onPress={() => {
                                console.log('11');
                            }}
                        >
                            <Text style={styles.rowBtn} />
                        </TouchableOpacity>
                        <View style={styles.bottomContent}>
                            <View style={styles.titleStyle}>
                                <View style={styles.titleStyleLeftContainer}>
                                    <Image source={avatar} style={styles.avatar} />
                                    <Text style={styles.leftStyle}>{detail.user.nickname}</Text>
                                </View>
                                {!showOther ? null : (
                                    <TouchableOpacity
                                        activeOpacity={0.6}
                                        onPress={() => {
                                            navigation.navigate('SelfWork', { _id: detail.user._id });
                                        }}
                                    >
                                        <View style={styles.rightStyle}>
                                            <Text style={styles.rightTextStyle}>他的作品</Text>
                                        </View>
                                    </TouchableOpacity>
                                )}
                            </View>

                            <View style={[styles.titleStyle, { marginTop: 30 }]}>
                                <View style={styles.titleStyleLeftContainer}>
                                    <Text style={[styles.leftStyle, { fontSize: 23 }]}>{detail.title}</Text>
                                </View>
                            </View>
                            <Text style={styles.contentStyle}>{detail.desc}</Text>
                            <View style={styles.down}>
                                <View style={styles.downContent}>
                                    <Image source={downLoad} style={[styles.imgStyle]} />
                                    <Text style={styles.downText}>{detail.totalDown}</Text>
                                </View>
                                <TouchableOpacity activeOpacity={0.6} onPress={this.focus}>
                                    <View style={styles.downContent}>
                                        <Image
                                            source={dz}
                                            style={[
                                                styles.imgStyle,
                                                detail.currentUserIsFocus ? { tintColor: 'red' } : {},
                                            ]}
                                        />
                                        <Text style={styles.downText}>{detail.focusUserCount}</Text>
                                    </View>
                                </TouchableOpacity>

                                <View style={styles.downContent}>
                                    <Image source={share} style={styles.imgStyle} />
                                    <Text style={styles.downText}>323</Text>
                                </View>
                            </View>
                            <View style={styles.btnBottomContainer}>
                                <View style={styles.btnBottom}>
                                    <TouchableOpacity activeOpacity={0.6} onPress={this.focus}>
                                        <View style={styles.leftBtn}>
                                            <Image
                                                source={sc}
                                                style={[
                                                    styles.imgBtnStyle,
                                                    detail.currentUserIsFocus ? { tintColor: 'red' } : {},
                                                ]}
                                            />
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={0.6} onPress={this.saveToCameraroll}>
                                        <View style={styles.rightBtn}>
                                            <Text style={styles.btnText}>下载壁纸</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    </Animatable.View>
                </SafeAreaView>
            </ImageBackground>
        );
    }
}
